package com.nuumoblie.bluetoothtools.bt;

import android.bluetooth.BluetoothDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.nuumoblie.bluetoothtools.R;

import java.util.List;

public class DevicesListAdapter extends RecyclerView.Adapter<DevicesListAdapter.ViewHolder> {

    private List<BluetoothDevice> mDevices = null;
    private Listener mListener = null;

    public DevicesListAdapter(Listener listener) {
        this.mListener = listener;
    }

    public void setDevices(List<BluetoothDevice> devices) {
        this.mDevices = devices;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public DevicesListAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.devices_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull DevicesListAdapter.ViewHolder holder, int position) {
        holder.setDeviceInfo(mDevices.get(position));
    }

    @Override
    public int getItemCount() {
        return mDevices == null ? 0 : mDevices.size();
    }

    class ViewHolder extends RecyclerView.ViewHolder {

        private TextView mTvName;
        private TextView mTvAdrees;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            mTvName = itemView.findViewById(R.id.tv_name);
            mTvAdrees = itemView.findViewById(R.id.tv_addr_info);
        }

        public void setDeviceInfo(final BluetoothDevice device) {
            mTvName.setText(device.getName());
            mTvAdrees.setText(device.getAddress() + (device.getBondState() == 10 ? "未匹配" : "匹配"));
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mListener != null) {
                        mListener.onItemClick(device);
                    }
                }
            });
        }
    }

    public interface Listener {
        void onItemClick(BluetoothDevice dev);
    }
}
